package com.zz.comframe.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import treemap.zz.json.JSONObject;

import com.zz.comframe.CommonDataProcesser;
import com.zz.comframe.properties.PropertiesPool;

public class save extends HttpServlet { // 提供零散数据访问，json形式返回记录

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		// 登录检查
		Object zz = request.getSession().getAttribute("user1");

		if (zz == null) { // 先检查用户是否处于登入状态
			response.sendRedirect("logout.jsp");
			return;
		}

		if(!PropertiesPool.CheckRequestParameters(request)){	
			out.print("{\"success\":false,\"errors\":[{\"id\":\"checkcode\",\"msg\":\"请求中含有非法字符！\"}]}");			
			return;
		}

		String id = request.getParameter("id");
		String oper = request.getParameter("oper");
		String term = request.getParameter("term");
		String sql = "";
		JSONObject extpar;
		try {
			extpar = "del".equalsIgnoreCase(oper)? null : new JSONObject(request.getParameter("extpar"));

			if (id == null || oper == null || "".equals(id) || "".equals(oper) //|| !PropertiesPool.SQLInjectionValid(id) 
					|| (!"del".equalsIgnoreCase(oper) && (extpar == null || extpar.length() <= 0 )))
				return;

			Iterator<?> ik = request.getParameterMap().keySet().iterator();
			Map<String, Object> parsmap = new HashMap<String, Object>();
			while (ik.hasNext()) {
				String col = (String) ik.next();
				if (col != null) {
					if ("col".equalsIgnoreCase(col.substring(0, Math.min(3, col.length())))) { // "COLXX"
						Object val = request.getParameter(col);
						if (val != null && !"".equals(val))
							parsmap.put(col, val);
					}
				}
			}
			String t = parsmap.toString();
//			if (!PropertiesPool.SQLInjectionValid(t))
//				return;

			if (oper.equalsIgnoreCase("add") && id.equalsIgnoreCase("new_row") && parsmap.size() > 0) {
				if(term==null || "".equals(term.trim()))	
					return;
				else{
					parsmap.put(PropertiesPool.getCommonpro("TERM_COLUMN_NAME"), term);
					extpar.put(PropertiesPool.getCommonpro("TERM_COLUMN_NAME"), "string");
				}

				sql = PropertiesPool.getCommonpro("SQL_INST_PERINFO");
				String cols = "COL0";
				String values = "'"+PropertiesPool.getUUidstr()+"'";
				Iterator<String> itkey = parsmap.keySet().iterator();
				while (itkey.hasNext()) {
					String key = itkey.next();
					String val = parsmap.get(key).toString();
					//boolean作为字符串处理
					val = Pattern.compile("true|yes", Pattern.CASE_INSENSITIVE).matcher(val.trim()).matches()?"true":val;
					val = Pattern.compile("false|no", Pattern.CASE_INSENSITIVE).matcher(val.trim()).matches()?"false":val;
					if (val == null || "null".equalsIgnoreCase(val.trim())){
						cols += "," + key ;
						values += ",NULL ";
					}else if (Pattern.compile("string|text|date", Pattern.CASE_INSENSITIVE).matcher(extpar.getString(key).trim()).matches()){
						cols += " ," + key;
						values += ",'" + val + "'";
					}else{
						cols += " ," + key;
						values += "," + val ;				
					}
				}
				sql = sql.replace("(col)", "(" + cols + ")"); // ???
				sql = sql.replace("(?)", "(" + values + ")"); // ???
				System.out.println(sql);
			} else if (oper.equalsIgnoreCase("del")) {
				sql = PropertiesPool.getCommonpro("SQL_DEL_PERINFO");
				sql = sql.replace("0=1", "COL0='" + id + "'"); // ???
				// dp.remove(sql, Long.parseLong(id));
				System.out.println(sql);
			} else if (oper.equalsIgnoreCase("edit") && parsmap.size() > 0) {
				sql = PropertiesPool.getCommonpro("SQL_UPDATE_PERINFO");
				String cols = " COL0='" + id + "' ";
				Iterator<String> itkey = parsmap.keySet().iterator();
				while (itkey.hasNext()) {
					//if(term!=null && !"".equals(term.trim()))	修改学期数据，暂时不需要
					//	parsmap.put(PropertiesPool.getCommonpro("TERM_COLUMN_NAME"), term);
					String key = itkey.next();
					String value = parsmap.get(key).toString();
					value = value==null?"null":value;
					//boolean作为字符串处理
					value = Pattern.compile("true|yes", Pattern.CASE_INSENSITIVE).matcher(value.trim()).matches()?"true":value;
					value = Pattern.compile("false|no", Pattern.CASE_INSENSITIVE).matcher(value.trim()).matches()?"false":value;

					if (value == null || "null".equalsIgnoreCase(value.trim()))
						cols += "," + key + "=NULL ";
					else if (Pattern.compile("string|text|date", Pattern.CASE_INSENSITIVE).matcher(extpar.getString(key).trim()).matches())
						cols += "," + key + "=" + "'" + value + "' ";
					else
						cols += "," + key + "=" + value + " ";
				}
				sql = sql.replace(":replace", cols); // ???
				sql = sql.replace("0=1", "COL0='" + id + "'"); // ???
				System.out.println(sql);
			}
			
			CommonDataProcesser dp = new CommonDataProcesser();
			if(dp.dosql(sql, null))	
				out.print("{\"success\":true,\"msg\":\"数据操作成功\"}");
			else
				out.print("{\"success\":false,\"msg\":\"错误数据或数据库关闭\"}");
		} catch (Exception e) {
			
			e.printStackTrace();
			out.print("{\"success\":false,\"msg\":\"数据异常错误\"}");

		}
	}
}
